﻿#include "GodPart.h"
#include "Common/TableData/GodGodCfg.h"
#include "Common/TableData/GodNumCfg.h"
#include "Common/AttrMgr/AttrMgr.h"
#include "PackagePart.h"
#include "Character/welfare/OperateWelfarePart.h"
#include "Player.h"

using namespace ProtoBuf;
GodPart::GodPart()
{

}

GodPart::~GodPart()
{

}

bool GodPart::Init(Creature *pMaster, uint32_t partType, CharacterDBInfo* pCharacterDB)
{
	Part::Init(pMaster, partType);
	m_mapGod.clear();
	const CharacterDBGodInfo & godInfo = pCharacterDB->goddata();
	for (int32_t i = 0; i < godInfo.godinfo_size(); i++)
	{
		const CharacterGodStruct& stGodInfo = godInfo.godinfo(i);
		
		if (m_mapGod.find(stGodInfo.id())==m_mapGod.end())
		{
			m_mapGod[stGodInfo.id()] = stGodInfo;

			AddAttr(stGodInfo.id(),stGodInfo.level());
		}
		else
		{
			LogErrFmtPrint("GodPart::Init error id=%d", stGodInfo.id());
		}
	}

	return true;
}
bool GodPart::UnInit()
{
	m_mapGod.clear();
	return true;
}
bool GodPart::OnMsgHandle(uint32_t cmd, const char* data, uint32_t len)
{

	if (cmd == CLIENT_TO_LOGIC_GOD_LIST)
	{
		C2GetGodList(data,len);
	}
	else if (cmd == CLIENT_TO_LOGIC_GOD_LEVEL)
	{
		C2GodLevel(data,len);
	}

	return true;
}


void GodPart::C2GetGodList(const char* data, uint32_t len)
{
	PlayerGodListRsp msg;
	for (mapGodInfo::iterator iter = m_mapGod.begin(); iter != m_mapGod.end();++iter)
	{
		CharacterGodStruct *pInfo =   msg.add_godinfo();
		pInfo->CopyFrom(iter->second);
	}

	m_pMaster->SendDataToClient(LOGIC_TO_CLIENT_GOD_LIST, &msg);
}
void GodPart::C2GodLevel(const char* data, uint32_t len)
{
	PlayerGodLevelReq msg;
	PlayerGodLevelRsp rspMsg;
	if (!msg.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] GodPart::C2GodLevel parse failed...");
		return;
	}
	rspMsg.set_ret(RET_FAIL);

	std::vector<int32_t> result;
	CharacterGodStruct stInfo;
	std::vector<string> vStr;
	uint32_t requestLevel = 0;
	int32_t bindNum = 0;
	int32_t notBindNum = 0;
	int32_t allNum = 0;
	int32_t itemNum = 0;
	int32_t goldNum = 0;
	//const GodGodCfgInfo * pConfigOther = nullptr;
	//先判断该ID是否存在
	const GodGodCfgInfo * pConfig=g_GetGodGodCfgTable()->GetGodGodCfgInfo(msg.godid());
	MMO_PROCESS_ERROR(pConfig);

	//再判断该ID的升级条件是否达到,分情况，如果是1级的判断人物等级，其它级的看填写的相关ID的等级
	if (pConfig->cengJi ==1)
	{
		result.clear();
		CommonApi::SplitStrToVecInt(pConfig->tiaoJian, ",", &result);

		if (m_mapGod.find(msg.godid()) == m_mapGod.end())
		{
			if (result.size()>0 && result[0] <= m_pMaster->GetPAttrValue(P_LEVEL))
			{
				//可以升级
				requestLevel = 1;
			}
			else
			{
				//等级不足
				rspMsg.set_ret(RET_GOD_PLAYER_LEVEL_NOT_ENOUGH);
				MMO_PROCESS_ERROR(false);
			}
		}
		else
		{
			stInfo = m_mapGod[msg.godid()];
			if (result.size() <= stInfo.level())
			{
				rspMsg.set_ret(RET_GOD_MAX_LEVEL);
				MMO_PROCESS_ERROR(false);
			}
			else
			{
				if (result[stInfo.level()] <= m_pMaster->GetPAttrValue(P_LEVEL))
				{
					requestLevel = stInfo.level()+1;
				}
				else
				{
					rspMsg.set_ret(RET_GOD_PLAYER_LEVEL_NOT_ENOUGH);
					MMO_PROCESS_ERROR(false);
				}
			}
		}
	}
	else
	{
		
		uint32_t minLevel = 100;
		//uint32_t maxLevel = 100;
		StringSplit(pConfig->tiaoJian, '|', vStr);
		for (int i = 0; i < (int)vStr.size(); ++i)
		{
			result.clear();
			CommonApi::SplitStrToVecInt(vStr[i], ",", &result);
			if (result.size()!=2)
			{
				LogErrFmtPrint("god config error godid=%d not %2 ==0  ",msg.godid());
				return;
			}
			if (m_mapGod.find(result[0])==m_mapGod.end())
			{
				rspMsg.set_ret(RET_GOD_OTHER_GOD_LEVEL_NOT_ENOUGH);
				MMO_PROCESS_ERROR(false);
			}
			CharacterGodStruct stInfo = m_mapGod[result[0]];
			if (minLevel>stInfo.level()/result[1])
			{
				minLevel = stInfo.level() / result[1];
			}
		}

		if (minLevel<=0)
		{
			rspMsg.set_ret(RET_GOD_OTHER_GOD_LEVEL_NOT_ENOUGH);
			MMO_PROCESS_ERROR(false);
		}

		if (m_mapGod.find(msg.godid()) == m_mapGod.end())
		{
			requestLevel = 1;
		}
		else
		{
			if (m_mapGod[msg.godid()].level()>=minLevel)
			{
				rspMsg.set_ret(RET_GOD_OTHER_GOD_LEVEL_NOT_ENOUGH);
				MMO_PROCESS_ERROR(false);
			}
			else
			{
				requestLevel = m_mapGod[msg.godid()].level() + 1;
			}
		}
	}

	if (requestLevel>0)
	{
		//扣消耗
		result.clear();
		CommonApi::SplitStrToVecInt(pConfig->caiLiaoShu, ",", &result);
		MMO_PROCESS_ERROR(result.size()>=requestLevel);
		itemNum = result[requestLevel-1];
		PackagePart * pPart = dynamic_cast<PackagePart*>(m_pMaster->GetPart(PART_PACKAGE));
		MMO_PROCESS_ERROR(pPart);

		allNum = pPart->GetItemNum(pConfig->caiLiao, bindNum, notBindNum);
		if (allNum<itemNum)
		{
			rspMsg.set_ret(RET_PACKAGE_ITEM_NUM_LACK);
			MMO_PROCESS_ERROR(false);
		}
		//金币
		result.clear();
		CommonApi::SplitStrToVecInt(pConfig->jinBiShu, ",", &result);
		MMO_PROCESS_ERROR(result.size() >= requestLevel);
		goldNum = result[requestLevel - 1];                //pow(result[0] / 10000.0 , requestLevel)* result[1] / 10000.0 ;
		if (goldNum>m_pMaster->GetAttr(C_GOLD))
		{
			rspMsg.set_ret(RET_MONEY_LACK);
			MMO_PROCESS_ERROR(false);
		}

		//扣东西
		SItemSourceParam sourceParam;
		sourceParam.source = S_GOD;
		pPart->RemoveItem(pConfig->caiLiao, itemNum, sourceParam);
		//m_pMaster->AddAttr(C_GOLD, -1 * goldNum,false);
		m_pMaster->AddSourceAttr(C_GOLD, -1 * goldNum, false, S_GOD);
	
		//减属性
		if (m_mapGod.find(msg.godid())!=m_mapGod.end())
		{
			AddAttr(m_mapGod[msg.godid()].id(), m_mapGod[msg.godid()].level(),false);
		}
		//再加这个的属性
		m_mapGod[msg.godid()].set_level(requestLevel);
		m_mapGod[msg.godid()].set_id(msg.godid());

		AddAttr(m_mapGod[msg.godid()].id(), m_mapGod[msg.godid()].level(), true);

		rspMsg.set_ret(RET_SUCCESS);	

		m_pMaster->SynAttrToClient();

		Player* pPlayer = static_cast<Player*>(m_pMaster);
		if (pPlayer != nullptr)
			pPlayer->GodLog(pConfig->caiLiao, itemNum, goldNum, pConfig->name, requestLevel);
	}
Exit0:
	rspMsg.set_godid(msg.godid());
	rspMsg.set_level(requestLevel);
	//返回消息
	m_pMaster->SendDataToClient(LOGIC_TO_CLIENT_GOD_LEVEL_RESULT, &rspMsg);

	//发送神格升级事件
	if (rspMsg.ret() == RET_SUCCESS)
	{
		uint32_t totalLel = 0;
		SET_UINT32 lelSet;
		for (mapGodInfo::iterator iter = m_mapGod.begin(); iter != m_mapGod.end(); ++iter)
		{
			totalLel += iter->second.level();
			lelSet.insert(iter->second.level());
		}

		GodLevelEvent godEvent;
		godEvent.godID = msg.godid();
		godEvent.level = requestLevel;
		godEvent.count = itemNum;
		godEvent.totalLel = totalLel;
		g_GetEvent()->FireExecute(EVENT_GOD_LEVEL, m_pMaster->GetCid(), CREATURE_PLAYER, (GodLevelEvent*)&godEvent, sizeof(GodLevelEvent));

		//七日目标活动
		OperateWelfarePart *pWelfarePart = dynamic_cast<OperateWelfarePart*>(m_pMaster->GetPart(PART_WELFARE));
		if (nullptr != pWelfarePart && pWelfarePart->Goals7DaysNeedStatics())
		{
			pWelfarePart->Goals7DaysUpdate(Goals7DayType_God, Goals7DayUpdateType_Total, Goals7DaySubType_GodSingleLel, requestLevel, msg.godid());
			pWelfarePart->Goals7DaysUpdate(Goals7DayType_God, Goals7DayUpdateType_Total, Goals7DaySubType_GodTotalLel, totalLel);
			pWelfarePart->Goals7DaysUpdate(Goals7DayType_God, Goals7DayUpdateType_Total, Goals7DaySubType_GodAverageLel, *lelSet.begin());
		}
	}

	return;
}


//增加或减少一个神格的属性
void GodPart::AddAttr(uint32_t godID, uint32_t level, bool addFlag)
{
	std::vector<int32_t> result;
	const GodNumCfgMap * pCfgMap = g_GetGodNumCfgTable()->GetGodNumCfgMap();
	if (pCfgMap)
	{
		for (GodNumCfgMap::const_iterator iter = pCfgMap->begin(); iter != pCfgMap->end();++iter)
		{
			if (iter->second.shenGeId == (int32_t)godID && iter->second.zhiYe == (int32_t)m_pMaster->GetAttr(C_PROF))
			{
				//计算
				for (int i = 0; i < (int)iter->second.vecGodNumShuXinCfg.size();++i)
				{
					result.clear();
					CommonApi::SplitStrToVecInt(iter->second.vecGodNumShuXinCfg[i].nu, ",", &result);

					if (result.size() <= 0)
					{
						continue;
					}

					if ((int)result.size()!=3)
					{
						LogDebugFmtPrint("GodPart::AddAttr god_num=%d param error ",iter->second.id);
						continue;
					}
					//计算公式
					uint32_t value = result[0]/10000.0 * level*level + result[1]/10000.0 * level + result[2]/10000.0;

					if (addFlag)
					{
						m_pMaster->AddAttr(g_GetAttrMgr()->GetPlayerFightModlePAttr(enFightAttrModule_God, iter->second.vecGodNumShuXinCfg[i].id), value,false);
					}
					else
					{
						m_pMaster->AddAttr(g_GetAttrMgr()->GetPlayerFightModlePAttr(enFightAttrModule_God, iter->second.vecGodNumShuXinCfg[i].id), -1*value, false);
					}
				}
			}
		}
	}
}

void GodPart::OnExecute(uint16_t nEventID, uint64_t nSrcID, uint8_t bySrcType, void *pContext, int32_t nLen)
{

}
void GodPart::OnTimer(uint32_t nTimerID)
{

}
bool GodPart::SynClient(PlayerClientInfo& playerInfo)
{
	return true;
}
bool GodPart::SaveDB(CharacterDBInfo& characterDB)
{
	characterDB.clear_goddata();
	CharacterDBGodInfo* godInfo = characterDB.mutable_goddata();
	for (mapGodInfo::iterator iter = m_mapGod.begin(); iter != m_mapGod.end(); ++iter)
	{
		CharacterGodStruct* pSingleHuoYueDuInfo = godInfo->add_godinfo();
		pSingleHuoYueDuInfo->CopyFrom(iter->second);
	}
	return true;
}

//获取指定神格等级
uint32_t GodPart::GetGodLevel(uint32_t godId)
{
	mapGodInfo::iterator iter = m_mapGod.find(godId);
	if (iter!=m_mapGod.end())
	{
		return iter->second.level();
	}
	return 0;
}